package com.oauth.model;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import com.oauth.model.AuthUrl;
import com.oauth.model.Website;

import android.util.Log;

public class OAuth2 extends OAuth {

//	private String app_id;
//	private String app_secret;
//	private String callbackUrl;
//	private String authorizekUrl;
//	private String accessUrl;

	private Website ws;

//	public OAuth2(String app_id, String app_secret, String callbackUrl,
//			String authorizekUrl, String accessUrl) {
//		super();
//		this.app_id = app_id;
//		this.app_secret = app_secret;
//		this.callbackUrl = callbackUrl;
//		this.authorizekUrl = authorizekUrl;
//		this.accessUrl = accessUrl;
//	}

	public OAuth2(Website ws) {
		super();
		this.ws = ws;
	}

	@Override
	public String authorize() {

		// List<NameValuePair> params = new ArrayList<NameValuePair>();
		//
		// params.add(new BasicNameValuePair("client_id", this.app_id));
		//
		// params.add(new BasicNameValuePair("response_type", "code"));
		//
		// params.add(new BasicNameValuePair("redirect_uri", this.callbackUrl));
		StringBuffer queryBuffer = new StringBuffer("?");
		List<NameValuePair> params = ws.auth.getParams();
		for (int i = 0; i < params.size(); i++) {
			queryBuffer.append(params.get(i).getName());
			queryBuffer.append("=");
			queryBuffer.append(params.get(i).getValue());
			queryBuffer.append("&");
		}
		queryBuffer.append("client_id=");
		queryBuffer.append(ws.app_key);
		queryBuffer.append("&");
		queryBuffer.append("redirect_uri=");
		queryBuffer.append(ws.redirect_uri);
		String queryString = queryBuffer.toString();
		return ws.auth.url + queryString;
		// return authorizekUrl + "?client_id=" + this.app_id /*
		// * +
		// * "&response_type=code"
		// */
		// + "&redirect_uri=" + this.callbackUrl/* +"&display=mobile" */;
	}

	@Override
	public String getAccessToken(NameValuePair[] code) {

		Log.i("DEBUG", "Code is: " + code);
		if (ws.accessToken.method_type == AuthUrl.METHOD_POST_BODY) {
			
			List<NameValuePair> params = new ArrayList<NameValuePair>(
					ws.accessToken.getParams());

			params.add(new BasicNameValuePair("client_id", ws.app_key));
			params.add(new BasicNameValuePair("redirect_uri", ws.redirect_uri));
			params.add(new BasicNameValuePair("client_secret", ws.app_secret));

			params.add(new BasicNameValuePair("code", code[0].getValue()));

			accessToken = doPostEntity(ws.accessToken.url, params);
			
		}
		return accessToken;
		// return this.accessUrl + "?client_id=" + this.app_id +
		// "&redirect_uri="
		// + this.callbackUrl + "&type=client_cred" + "&client_secret="
		// + this.app_secret + "&code=" + code;
	}

}
